package com.alogic.xscript.plugins;

import org.apache.commons.lang3.StringUtils;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.code.Coder;
import com.anysoft.util.code.CoderFactory;

/**
 * 解密
 * 
 * @author duanyy
 * @since 1.6.5.13
 * @version 1.6.8.14 [20170509 duanyy] <br>
 * - 增加xscript的中间文档模型,以便支持多种报文协议 <br>
 */
public class Decrypt extends AbstractLogiclet{
	protected String $in = NULL;
	protected String $id = NULL;
	protected String $coder = CoderFactory.DFT_CODER;
	protected String $key = NULL;
	protected String $hex = FALSE;
	protected String $urlSafe = TRUE;

	public Decrypt(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p) {
		super.configure(p);

		$in = PropertiesConstants.getRaw(p,"in", $in);
		$id = PropertiesConstants.getRaw(p,"id", "$" + this.getXmlTag());
		$key = PropertiesConstants.getRaw(p,"key", $key);
		$coder = PropertiesConstants.getRaw(p,"coder", $coder);
		$hex = PropertiesConstants.getRaw(p,"hex", $hex);
		$urlSafe = PropertiesConstants.getRaw(p,"urlSafe", $urlSafe);
	}

	@Override
	protected void onExecute(XsObject root,XsObject current, LogicletContext ctx,
							 ExecuteWatcher watcher) {

		String inData = ctx.transform($in);
		String keyData = ctx.transform($key);

		if (StringUtils.isNotEmpty(inData)){
			Coder c = CoderFactory.newCoder(PropertiesConstants.transform(ctx,$coder,"DES3"));
			String outData = c.decode(inData, keyData,
					PropertiesConstants.transform(ctx,$hex,false),
					PropertiesConstants.transform(ctx,$urlSafe,true)
			);
			String outId = ctx.transform($id);
			if (StringUtils.isNotEmpty(outData) && StringUtils.isNotEmpty(outId)){
				ctx.SetValue(outId, outData);
			}
		}
	}
}
